/**
 * 封装 axios
 *
 * @author 俞杰
 * @email 158392613@qq.com
 */

import axios, { AxiosError } from 'axios'
import config from '@/config'
import { handleNetworkError, handleResponse } from './responseHandler'
import { handleMockMode } from './requestConfigHandler'
import useLoadState from '@/store/loadState'

const service = axios.create({
  baseURL: config.BASE_URL,
  isMock: config.isMock,
  timeout: 5000,
})

service.interceptors.request.use((requestConfig) => {
  useLoadState().startLoading(requestConfig.url)
  handleMockMode(requestConfig)
  return requestConfig
})

service.interceptors.response.use(
  (resp) => {
    useLoadState().finishLoading(resp.config.url)
    return handleResponse(resp)
  },
  (err: AxiosError) => {
    useLoadState().finishLoading(err.config.url)
    return handleNetworkError(err)
  }
)

export default service
